import sys

from PySide6.QtCore import Signal, QTimer
from PySide6.QtWidgets import QDialog, QApplication, QMessageBox

from backend.db.database import SessionLocal
from backend.schemas.member_pydantic import MemberUpdate
from backend.services.members_service import MemberService
from front.ui.ui_change_vip import Ui_Dialog


class ChangeVip(QDialog, Ui_Dialog):
    refresh = Signal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi(self)
        self.pushButton.clicked.connect(self.update_vip)
        self.debounce_timer = QTimer()
        self.debounce_timer.setSingleShot(True)  # 只触发一次
        self.debounce_timer.timeout.connect(self.fill_Edit)
        self.id_Edit.textChanged.connect(self.on_text_changed)

    def on_text_changed(self, text):
        # 每次输入都重置定时器：停止旧的，重新计时
        self.debounce_timer.stop()
        self.debounce_timer.start(300)  # 300毫秒后执行（可调整）

    def update_vip(self):
        try:
            with SessionLocal() as session:
                member_service = MemberService(session)
                phone = self.phone_Edit.text().strip()
                name = self.name_Edit.text().strip()
                member_id = self.id_Edit.text().strip()
                note = self.phone_Edit_2.text().strip()
                if not phone or not name or not member_id:
                    QMessageBox.warning(self, "警告", "缺少ID、姓名或联系方式")
                    return
                a = {"phone_num": phone, "name": name, "note": note}
                a = MemberUpdate(**a)
                member_service.update_member(member_id, a)
                QMessageBox.information(self, "成功", "修改成功")
                self.refresh.emit()
                self.deleteLater()
        except ValueError:
            QMessageBox.warning(self, "错误", "此会员ID不存在")

    def fill_Edit(self):
        """根据ID填充"""
        member_id_text = self.id_Edit.text().strip()

        if not member_id_text:
            # 可选：清空其他字段？
            self.name_Edit.clear()
            self.phone_Edit.clear()
            self.note_Edit.clear()
            return
        try:
            member_id = int(member_id_text)
        except ValueError:
            QMessageBox.warning(self, "输入错误", "会员ID必须是数字！")
            self.id_Edit.selectAll()  # 方便用户重新输入
            self.id_Edit.setFocus()
            return
        try:
            with SessionLocal() as session:
                member_service = MemberService(session)
                member_name = member_service.get_member_by_id(member_id)
                if member_name is None:
                    QMessageBox.warning(self, "未找到", f"ID 为 {member_id} 的会员不存在！")
                    self.id_Edit.selectAll()
                    self.id_Edit.setFocus()
                    self.name_Edit.clear()
                    self.phone_Edit.clear()
                    self.phone_Edit_2.clear()
                    return
                self.name_Edit.setText(member_name.name or "")
                self.phone_Edit.setText(member_name.phone or "")
                self.phone_Edit_2.setText(member_name.note or "")
        except Exception as e:
            # 捕获数据库或其他未知错误（用于调试）
            QMessageBox.critical(self, "系统错误", f"查询失败：{str(e)}")


if __name__ == '__main__':
    app = QApplication([])
    win = ChangeVip()
    win.show()
    sys.exit(app.exec())
